home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / urlparse.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  14KB  |  500 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''Parse (absolute and relative) URLs.
  5.  
  6. See RFC 1808: "Relative Uniform Resource Locators", by R. Fielding,
  7. UC Irvine, June 1995.
  8. '''
  9. __all__ = [
  10.     'urlparse',
  11.     'urlunparse',
  12.     'urljoin',
  13.     'urldefrag',
  14.     'urlsplit',
  15.     'urlunsplit',
  16.     'parse_qs',
  17.     'parse_qsl']
  18. uses_relative = [
  19.     'ftp',
  20.     'http',
  21.     'gopher',
  22.     'nntp',
  23.     'imap',
  24.     'wais',
  25.     'file',
  26.     'https',
  27.     'shttp',
  28.     'mms',
  29.     'prospero',
  30.     'rtsp',
  31.     'rtspu',
  32.     '',
  33.     'sftp']
  34. uses_netloc = [
  35.     'ftp',
  36.     'http',
  37.     'gopher',
  38.     'nntp',
  39.     'telnet',
  40.     'imap',
  41.     'wais',
  42.     'file',
  43.     'mms',
  44.     'https',
  45.     'shttp',
  46.     'snews',
  47.     'prospero',
  48.     'rtsp',
  49.     'rtspu',
  50.     'rsync',
  51.     '',
  52.     'svn',
  53.     'svn+ssh',
  54.     'sftp']
  55. non_hierarchical = [
  56.     'gopher',
  57.     'hdl',
  58.     'mailto',
  59.     'news',
  60.     'telnet',
  61.     'wais',
  62.     'imap',
  63.     'snews',
  64.     'sip',
  65.     'sips']
  66. uses_params = [
  67.     'ftp',
  68.     'hdl',
  69.     'prospero',
  70.     'http',
  71.     'imap',
  72.     'https',
  73.     'shttp',
  74.     'rtsp',
  75.     'rtspu',
  76.     'sip',
  77.     'sips',
  78.     'mms',
  79.     '',
  80.     'sftp']
  81. uses_query = [
  82.     'http',
  83.     'wais',
  84.     'imap',
  85.     'https',
  86.     'shttp',
  87.     'mms',
  88.     'gopher',
  89.     'rtsp',
  90.     'rtspu',
  91.     'sip',
  92.     'sips',
  93.     '']
  94. uses_fragment = [
  95.     'ftp',
  96.     'hdl',
  97.     'http',
  98.     'gopher',
  99.     'news',
  100.     'nntp',
  101.     'wais',
  102.     'https',
  103.     'shttp',
  104.     'snews',
  105.     'file',
  106.     'prospero',
  107.     '']
  108. scheme_chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-.'
  109. MAX_CACHE_SIZE = 20
  110. _parse_cache = { }
  111.  
  112. def clear_cache():
  113.     '''Clear the parse cache.'''
  114.     _parse_cache.clear()
  115.  
  116.  
  117. class ResultMixin(object):
  118.     '''Shared methods for the parsed result objects.'''
  119.     
  120.     def username(self):
  121.         netloc = self.netloc
  122.         if '@' in netloc:
  123.             userinfo = netloc.rsplit('@', 1)[0]
  124.             if ':' in userinfo:
  125.                 userinfo = userinfo.split(':', 1)[0]
  126.             
  127.             return userinfo
  128.  
  129.     username = property(username)
  130.     
  131.     def password(self):
  132.         netloc = self.netloc
  133.         if '@' in netloc:
  134.             userinfo = netloc.rsplit('@', 1)[0]
  135.             if ':' in userinfo:
  136.                 return userinfo.split(':', 1)[1]
  137.         
  138.  
  139.     password = property(password)
  140.     
  141.     def hostname(self):
  142.         netloc = self.netloc
  143.         if '@' in netloc:
  144.             netloc = netloc.rsplit('@', 1)[1]
  145.         
  146.         if ':' in netloc:
  147.             netloc = netloc.split(':', 1)[0]
  148.         
  149.         if not netloc.lower():
  150.             pass
  151.  
  152.     hostname = property(hostname)
  153.     
  154.     def port(self):
  155.         netloc = self.netloc
  156.         if '@' in netloc:
  157.             netloc = netloc.rsplit('@', 1)[1]
  158.         
  159.         if ':' in netloc:
  160.             port = netloc.split(':', 1)[1]
  161.             return int(port, 10)
  162.  
  163.     port = property(port)
  164.  
  165. from collections import namedtuple
  166.  
  167. class SplitResult(namedtuple('SplitResult', 'scheme netloc path query fragment'), ResultMixin):
  168.     __slots__ = ()
  169.     
  170.     def geturl(self):
  171.         return urlunsplit(self)
  172.  
  173.  
  174.  
  175. class ParseResult(namedtuple('ParseResult', 'scheme netloc path params query fragment'), ResultMixin):
  176.     __slots__ = ()
  177.     
  178.     def geturl(self):
  179.         return urlunparse(self)
  180.  
  181.  
  182.  
  183. def urlparse(url, scheme = '', allow_fragments = True):
  184.     """Parse a URL into 6 components:
  185.     <scheme>://<netloc>/<path>;<params>?<query>#<fragment>
  186.     Return a 6-tuple: (scheme, netloc, path, params, query, fragment).
  187.     Note that we don't break the components up in smaller bits
  188.     (e.g. netloc is a single string) and we don't expand % escapes."""
  189.     tuple = urlsplit(url, scheme, allow_fragments)
  190.     (scheme, netloc, url, query, fragment) = tuple
  191.     if scheme in uses_params and ';' in url:
  192.         (url, params) = _splitparams(url)
  193.     else:
  194.         params = ''
  195.     return ParseResult(scheme, netloc, url, params, query, fragment)
  196.  
  197.  
  198. def _splitparams(url):
  199.     if '/' in url:
  200.         i = url.find(';', url.rfind('/'))
  201.         if i < 0:
  202.             return (url, '')
  203.     else:
  204.         i = url.find(';')
  205.     return (url[:i], url[i + 1:])
  206.  
  207.  
  208. def _splitnetloc(url, start = 0):
  209.     delim = len(url)
  210.     for c in '/?#':
  211.         wdelim = url.find(c, start)
  212.         if wdelim >= 0:
  213.             delim = min(delim, wdelim)
  214.             continue
  215.     
  216.     return (url[start:delim], url[delim:])
  217.  
  218.  
  219. def urlsplit(url, scheme = '', allow_fragments = True):
  220.     """Parse a URL into 5 components:
  221.     <scheme>://<netloc>/<path>?<query>#<fragment>
  222.     Return a 5-tuple: (scheme, netloc, path, query, fragment).
  223.     Note that we don't break the components up in smaller bits
  224.     (e.g. netloc is a single string) and we don't expand % escapes."""
  225.     allow_fragments = bool(allow_fragments)
  226.     key = (url, scheme, allow_fragments, type(url), type(scheme))
  227.     cached = _parse_cache.get(key, None)
  228.     if cached:
  229.         return cached
  230.     if len(_parse_cache) >= MAX_CACHE_SIZE:
  231.         clear_cache()
  232.     
  233.     netloc = query = fragment = ''
  234.     i = url.find(':')
  235.     if i > 0:
  236.         if url[:i] == 'http':
  237.             scheme = url[:i].lower()
  238.             url = url[i + 1:]
  239.             if url[:2] == '//':
  240.                 (netloc, url) = _splitnetloc(url, 2)
  241.             
  242.             if allow_fragments and '#' in url:
  243.                 (url, fragment) = url.split('#', 1)
  244.             
  245.             if '?' in url:
  246.                 (url, query) = url.split('?', 1)
  247.             
  248.             v = SplitResult(scheme, netloc, url, query, fragment)
  249.             _parse_cache[key] = v
  250.             return v
  251.         for c in url[:i]:
  252.             if c not in scheme_chars:
  253.                 break
  254.                 continue
  255.             url[:i] == 'http'
  256.         else:
  257.             scheme = url[:i].lower()
  258.             url = url[i + 1:]
  259.     
  260.     if scheme in uses_netloc and url[:2] == '//':
  261.         (netloc, url) = _splitnetloc(url, 2)
  262.     
  263.     if allow_fragments and scheme in uses_fragment and '#' in url:
  264.         (url, fragment) = url.split('#', 1)
  265.     
  266.     if scheme in uses_query and '?' in url:
  267.         (url, query) = url.split('?', 1)
  268.     
  269.     v = SplitResult(scheme, netloc, url, query, fragment)
  270.     _parse_cache[key] = v
  271.     return v
  272.  
  273.  
  274. def urlunparse(data):
  275.     '''Put a parsed URL back together again.  This may result in a
  276.     slightly different, but equivalent URL, if the URL that was parsed
  277.     originally had redundant delimiters, e.g. a ? with an empty query
  278.     (the draft states that these are equivalent).'''
  279.     (scheme, netloc, url, params, query, fragment) = data
  280.     if params:
  281.         url = '%s;%s' % (url, params)
  282.     
  283.     return urlunsplit((scheme, netloc, url, query, fragment))
  284.  
  285.  
  286. def urlunsplit(data):
  287.     (scheme, netloc, url, query, fragment) = data
  288.     if (netloc or scheme) and scheme in uses_netloc and url[:2] != '//':
  289.         if url and url[:1] != '/':
  290.             url = '/' + url
  291.         
  292.         if not netloc:
  293.             pass
  294.         url = '//' + '' + url
  295.     
  296.     if scheme:
  297.         url = scheme + ':' + url
  298.     
  299.     if query:
  300.         url = url + '?' + query
  301.     
  302.     if fragment:
  303.         url = url + '#' + fragment
  304.     
  305.     return url
  306.  
  307.  
  308. def urljoin(base, url, allow_fragments = True):
  309.     '''Join a base URL and a possibly relative URL to form an absolute
  310.     interpretation of the latter.'''
  311.     if not base:
  312.         return url
  313.     if not url:
  314.         return base
  315.     (bscheme, bnetloc, bpath, bparams, bquery, bfragment) = urlparse(base, '', allow_fragments)
  316.     (scheme, netloc, path, params, query, fragment) = urlparse(url, bscheme, allow_fragments)
  317.     if scheme != bscheme or scheme not in uses_relative:
  318.         return url
  319.     if path[:1] == '/':
  320.         return urlunparse((scheme, netloc, path, params, query, fragment))
  321.     if not path:
  322.         path = bpath
  323.         if not params:
  324.             params = bparams
  325.         else:
  326.             path = path[:-1]
  327.             return urlunparse((scheme, netloc, path, params, query, fragment))
  328.         return urlunparse((scheme, netloc, path, params, query, fragment))
  329.     segments = bpath.split('/')[:-1] + path.split('/')
  330.     while '.' in segments:
  331.         segments.remove('.')
  332.         continue
  333.         url if scheme in uses_netloc else scheme not in uses_relative if segments[-1] == '.' else path[:1] == '/'
  334.     while None:
  335.         i = 1
  336.         n = len(segments) - 1
  337.         while i < n:
  338.             if segments[i] == '..' and segments[i - 1] not in ('', '..'):
  339.                 del segments[i - 1:i + 1]
  340.                 break
  341.             
  342.             i = i + 1
  343.         break
  344.         continue
  345.         if segments == [
  346.             '',
  347.             '..']:
  348.             segments[-1] = ''
  349.         elif len(segments) >= 2 and segments[-1] == '..':
  350.             segments[-2:] = [
  351.                 '']
  352.         
  353.     return urlunparse((scheme, netloc, '/'.join(segments), params, query, fragment))
  354.  
  355.  
  356. def urldefrag(url):
  357.     '''Removes any existing fragment from URL.
  358.  
  359.     Returns a tuple of the defragmented URL and the fragment.  If
  360.     the URL contained no fragments, the second element is the
  361.     empty string.
  362.     '''
  363.     if '#' in url:
  364.         (s, n, p, a, q, frag) = urlparse(url)
  365.         defrag = urlunparse((s, n, p, a, q, ''))
  366.         return (defrag, frag)
  367.     return (url, '')
  368.  
  369. _hextochr = dict((lambda .0: for i in .0:
  370. ('%02x' % i, chr(i)))(range(256)))
  371. _hextochr.update((lambda .0: for i in .0:
  372. ('%02X' % i, chr(i)))(range(256)))
  373.  
  374. def unquote(s):
  375.     """unquote('abc%20def') -> 'abc def'."""
  376.     res = s.split('%')
  377.     for i in xrange(1, len(res)):
  378.         item = res[i]
  379.         
  380.         try:
  381.             res[i] = _hextochr[item[:2]] + item[2:]
  382.         continue
  383.         except KeyError:
  384.             res[i] = '%' + item
  385.             continue
  386.             except UnicodeDecodeError:
  387.                 res[i] = unichr(int(item[:2], 16)) + item[2:]
  388.                 continue
  389.             
  390.         return ''.join(res)
  391.  
  392.  
  393.  
  394. def parse_qs(qs, keep_blank_values = 0, strict_parsing = 0):
  395.     '''Parse a query given as a string argument.
  396.  
  397.         Arguments:
  398.  
  399.         qs: URL-encoded query string to be parsed
  400.  
  401.         keep_blank_values: flag indicating whether blank values in
  402.             URL encoded queries should be treated as blank strings.
  403.             A true value indicates that blanks should be retained as
  404.             blank strings.  The default false value indicates that
  405.             blank values are to be ignored and treated as if they were
  406.             not included.
  407.  
  408.         strict_parsing: flag indicating what to do with parsing errors.
  409.             If false (the default), errors are silently ignored.
  410.             If true, errors raise a ValueError exception.
  411.     '''
  412.     dict = { }
  413.     for name, value in parse_qsl(qs, keep_blank_values, strict_parsing):
  414.         if name in dict:
  415.             dict[name].append(value)
  416.             continue
  417.         dict[name] = [
  418.             value]
  419.     
  420.     return dict
  421.  
  422.  
  423. def parse_qsl(qs, keep_blank_values = 0, strict_parsing = 0):
  424.     '''Parse a query given as a string argument.
  425.  
  426.     Arguments:
  427.  
  428.     qs: URL-encoded query string to be parsed
  429.  
  430.     keep_blank_values: flag indicating whether blank values in
  431.         URL encoded queries should be treated as blank strings.  A
  432.         true value indicates that blanks should be retained as blank
  433.         strings.  The default false value indicates that blank values
  434.         are to be ignored and treated as if they were  not included.
  435.  
  436.     strict_parsing: flag indicating what to do with parsing errors. If
  437.         false (the default), errors are silently ignored. If true,
  438.         errors raise a ValueError exception.
  439.  
  440.     Returns a list, as G-d intended.
  441.     '''
  442.     pairs = [ s2 for s1 in qs.split('&') for s2 in s1.split(';') ]
  443.     r = []
  444.     for name_value in pairs:
  445.         nv = name_value.split('=', 1)
  446.         if len(nv[1]) or keep_blank_values:
  447.             name = unquote(nv[0].replace('+', ' '))
  448.             value = unquote(nv[1].replace('+', ' '))
  449.             r.append((name, value))
  450.             continue
  451.         None if len(nv) != 2 else None if not name_value and not strict_parsing else []
  452.     
  453.     return r
  454.  
  455. test_input = '\n      http://a/b/c/d\n\n      g:h        = <URL:g:h>\n      http:g     = <URL:http://a/b/c/g>\n      http:      = <URL:http://a/b/c/d>\n      g          = <URL:http://a/b/c/g>\n      ./g        = <URL:http://a/b/c/g>\n      g/         = <URL:http://a/b/c/g/>\n      /g         = <URL:http://a/g>\n      //g        = <URL:http://g>\n      ?y         = <URL:http://a/b/c/d?y>\n      g?y        = <URL:http://a/b/c/g?y>\n      g?y/./x    = <URL:http://a/b/c/g?y/./x>\n      .          = <URL:http://a/b/c/>\n      ./         = <URL:http://a/b/c/>\n      ..         = <URL:http://a/b/>\n      ../        = <URL:http://a/b/>\n      ../g       = <URL:http://a/b/g>\n      ../..      = <URL:http://a/>\n      ../../g    = <URL:http://a/g>\n      ../../../g = <URL:http://a/../g>\n      ./../g     = <URL:http://a/b/g>\n      ./g/.      = <URL:http://a/b/c/g/>\n      /./g       = <URL:http://a/./g>\n      g/./h      = <URL:http://a/b/c/g/h>\n      g/../h     = <URL:http://a/b/c/h>\n      http:g     = <URL:http://a/b/c/g>\n      http:      = <URL:http://a/b/c/d>\n      http:?y         = <URL:http://a/b/c/d?y>\n      http:g?y        = <URL:http://a/b/c/g?y>\n      http:g?y/./x    = <URL:http://a/b/c/g?y/./x>\n'
  456.  
  457. def test():
  458.     import sys as sys
  459.     base = ''
  460.     if sys.argv[1:]:
  461.         fn = sys.argv[1]
  462.         if fn == '-':
  463.             fp = sys.stdin
  464.         else:
  465.             fp = open(fn)
  466.     else:
  467.         
  468.         try:
  469.             StringIO = StringIO
  470.             import cStringIO
  471.         except ImportError:
  472.             StringIO = StringIO
  473.             import StringIO
  474.  
  475.         fp = StringIO(test_input)
  476.     for line in fp:
  477.         words = line.split()
  478.         if not words:
  479.             continue
  480.         
  481.         url = words[0]
  482.         parts = urlparse(url)
  483.         print '%-10s : %s' % (url, parts)
  484.         abs = urljoin(base, url)
  485.         if not base:
  486.             base = abs
  487.         
  488.         wrapped = '<URL:%s>' % abs
  489.         print '%-10s = %s' % (url, wrapped)
  490.         if len(words) == 3 and words[1] == '=':
  491.             if wrapped != words[2]:
  492.                 print 'EXPECTED', words[2], '!!!!!!!!!!'
  493.             
  494.         wrapped != words[2]
  495.     
  496.  
  497. if __name__ == '__main__':
  498.     test()
  499.  
  500.